
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 800 - margin.left - margin.right,
    height = 600 - margin.top - margin.bottom;

/* 
 * value accessor - returns the value to encode for a given data object.
 * scale - maps value to a visual display encoding, such as a pixel position.
 * map function - maps from data value to display value
 * axis - sets up axis
 */ 

// setup x 
var xValue = function(d) { return d.Platemean;}, // data -> value
    xScale = d3.scale.linear().range([0, width]), // value -> display
    xMap = function(d) { return xScale(xValue(d));}, // data -> display
    xAxis = d3.svg.axis().scale(xScale).orient("bottom");

// setup y
var yValue = function(d) { return d.NTmean;}, // data -> value
    yScale = d3.scale.linear().range([height, 0]), // value -> display
    yMap = function(d) { return yScale(yValue(d));}, // data -> display
    yAxis = d3.svg.axis().scale(yScale).orient("left");

// setup fill color
var cValue = function(d) { return d.Condition;},
    color = d3.scale.category10();

// add the graph canvas to the body of the webpage
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// add the tooltip area to the webpage
var tooltip = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

draw_err(errdata);

// load data
function draw_err(data) {
  // change string (from CSV) into number format
  data.forEach(function(d) {
  if (d.Platemean > 1000000){
    d.Platemean = d.Platemean/1000000;
    d.Platestd = d.Platestd/1000000;
    d.NTmean = d.NTmean/1000000;
    d.NTstd = d.NTstd/1000000;}
  });

  
console.log(data);
  // don't want dots overlapping axis, so add in buffer to data domain
  xScale.domain([d3.min(data, xValue)-.4*d3.min(data, xValue), d3.max(data, xValue)+.4*d3.max(data, xValue)]);
  yScale.domain([d3.min(data, yValue)-.4*d3.min(data, yValue), d3.max(data, yValue)+.4*d3.max(data, yValue)]);


//The data for our line
 var lineData = [ { "x": xScale(d3.min(data, xValue)-.4*d3.min(data, xValue)),   "y": yScale(d3.min(data, xValue)-.3*d3.min(data, xValue))}, 
                  { "x": xScale(d3.max(data, xValue)+.4*d3.max(data, xValue)),   "y": yScale(d3.max(data, xValue)+.3*d3.max(data, xValue))}, ];

//This is the accessor function 
 var lineFunction = d3.svg.line()
                         .x(function(d) { return d.x; })
                         .y(function(d) { return d.y; })
                         .interpolate("linear");

  svg.append("path")
	    .attr("d", lineFunction(lineData))
	    .attr("stroke", "green")
	    .attr("stroke-width", 2)
	    .attr("fill", "none");

 var eb_y = errorBar(horizontal=false)
         .oldXScale(xScale)
         .xScale(xScale)
         .oldYScale(yScale)
         .yScale(yScale)
         .yValue(yMap)
         .xValue(xMap)
         .xError(function(d){return null})
         .yError(function(d){return d.NTstd});

 var eb_x = errorBar(horizontal=true)
         .oldXScale(xScale)
         .xScale(xScale)
         .oldYScale(xScale)
         .yScale(xScale)
         .yValue(xMap)
         .xValue(xMap)
         .xError(function(d){return null})
         .yError(function(d){return d.Platestd});



function openLink() {
		return function(d) {
			window.open("//" + "127.0.0.1:8000"+d.URL)
		}
	}

  // draw dots
  var data_dots=svg.selectAll("g").data(data);
	

  // draw x error bars
    dEnter_x=data_dots.enter().append("g")
              .attr("transform", function(d) {return "translate("+ xMap(d) +","+ yMap(d) +")"});
    dEnter_x.call(eb_x);

  // draw y error bars
    dEnter=data_dots.enter().append("g")
              .attr("transform", function(d) {return "translate("+ xMap(d) +","+ yMap(d) +")"});
    dEnter.call(eb_y);
    

    dEnter.append("rect")
      .attr("transform", function(d) {return "translate(-4, -4)"})
      .attr("class", "dot")
      .attr("width", 8)
      .attr("height", 8)
      .style("fill", function(d) { return color(cValue(d));}) 
      .on("click", openLink())
      .on("mouseover", function(d) {
	  d3.select(this)
	  .classed({"hldot": true, "dot": false});

          tooltip.transition()
               .duration(100)
               .style("opacity", .9);
          tooltip.html(d["Platename"] + "<br/> Plate Mean: " + xValue(d) 
	        + ", <br/> NT Mean: " + yValue(d))
               .style("left", (d3.event.pageX + 5) + "px")
               .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
	  d3.select(this)
	  .classed({"dot": true, "hldot": false});
          tooltip.transition()
               .duration(500)
               .style("opacity", 0);
      });


// add a title
	svg.append("text")
        .attr("x", (width / 2))             
        .attr("y", 0 + (margin.top / 2))
        .attr("text-anchor", "middle")  
        .style("font-size", "18px") 
        //.style("text-decoration", "underline")  
        .text("Negative control mean vs plate mean");

  // x-axis
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("class", "label")
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text("Plate Mean (million)");

  // y-axis
  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("class", "label")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("NT mean (million)");

  // draw legend
  var legend = svg.selectAll(".legend")
      .data(color.domain())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  // draw legend colored rectangles
  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  // draw legend text
  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d+' Plate';})
}

